<template>
  <div class="edit-pim-container">
    <div class="edit-pim-box">
      <h3 class="edit-pim-title">编辑个人信息</h3>
      <el-form :model="userInfo" ref="userInfoFormRef" label-width="120px">
        <el-form-item label="登录名" prop="username" :rules="[{ required: true, message: '请输入登录名', trigger: 'blur' }]">
          <el-input type="text" v-model="userInfo.username" size="small" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input type="password" v-model="userInfo.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" :rules="[
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ]">
          <el-input type="password" v-model="userInfo.confirmPassword" show-password></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="nickname" :rules="[{ required: true, message: '请输入真实姓名', trigger: 'blur' }]">
          <el-input type="text" v-model="userInfo.nickname" size="small"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" :rules="[{ required: true, message: '请选择性别', trigger: 'blur' }]">
          <el-select v-model="userInfo.sex" placeholder="请选择性别" size="small">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :rules="[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
        ]">
          <el-input type="email" v-model="userInfo.email" size="small"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber" :rules="[
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的电话号码', trigger: 'blur' }
        ]">
          <el-input type="text" v-model="userInfo.phoneNumber" size="small"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="update-button" type="primary" @click="updateUserInfo">更新信息</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import router from "@/util/router";
import http from '@/axios/http';

const userInfoFormRef = ref(null); // 用于表单验证
const errorMsg = ref(''); // 使用 ref 创建响应式变量
const userInfo = ref({
  id: null,
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  sex: null,
  email: '',
  phoneNumber: ''
});

// 验证两次密码是否一致
function validatePassword(rule, value, callback) {
  if (value !== userInfo.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}

// 获取用户信息
function fetchUserInfo() {
  const userId = localStorage.getItem('userId'); // 从本地存储获取用户ID
  if (userId) {
    http.post('/get_user_list', { id: userId }).then((res) => {
      const result = res.data;
      if (result.result === "success" && result.data) {
        const user = result.data;
        Object.assign(userInfo.value, {
          id: user.id,
          username: user.username,
          password: '',
          confirmPassword: '',
          nickname: user.nickname,
          sex: user.sex,
          email: user.email,
          phoneNumber: user.phoneNumber
        });
      }
    }).catch((error) => {
      console.error("获取用户信息失败", error);
      errorMsg.value = "获取用户信息失败，请稍后再试";
    });
  }
}

// 更新用户信息逻辑
function updateUserInfo() {
  // 验证表单
  userInfoFormRef.value.validate((valid) => {
    if (!valid) {
      return; // 如果验证不通过，直接返回
    }

    const updateData = {
      ...userInfo.value,
      password: userInfo.value.password, // 如果不需要更新密码，可以忽略这行
      confirmPassword: '' // 不需要发送确认密码
    };

    http.post('/edit_user', updateData).then((res) => {
      const result = res.data;
      if (result.result === "success") {
        router.push('/login');
      } else {
        errorMsg.value = result.error || "更新信息失败，请稍后再试";
      }
    }).catch((error) => {
      console.error("更新信息请求失败", error);
      errorMsg.value = "更新信息请求失败，请稍后再试";
    });
  });
}

onMounted(() => {
  fetchUserInfo();
});

</script>
<style scoped>
.edit-pim-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.edit-pim-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.edit-pim-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.el-form-item {
  margin-bottom: 20px;
}

.update-button {
  width: 100%;
  margin-top: 10px;
}
</style>